package de.baumann.browser.fragments

import android.view.View
import de.baumann.browser.R
import de.baumann.browser.activitys.oc.OcWalletDetailActivity
import de.baumann.browser.base.BaseOdinFragment
import de.baumann.browser.db.ETHWallet
import de.baumann.browser.iview.ImportWalletView
import de.baumann.browser.present.ImportWalletPresenter
import de.baumann.browser.utils.saveMoneyAddress
import de.baumann.browser.utils.saveWalletName
import kotlinx.android.synthetic.main.fragment_import_keystore.*


class ImportKeystoreFragment : BaseOdinFragment<ImportWalletView, ImportWalletPresenter>(), ImportWalletView {

    companion object {
        val instance: ImportKeystoreFragment by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            ImportKeystoreFragment()
        }
    }

    override fun getLayout(): Int {
        return R.layout.fragment_import_keystore
    }

    override fun initView(view: View) {
        btnImportKeystore.setOnClickListener {
            if (getKeyStore().isEmpty()) {
                super.onError("请输入Keystore")
                return@setOnClickListener
            }

            if (getKeystorePwd().isEmpty()) {
                super.onError("请输入钱包密码")
                return@setOnClickListener
            }
            showLoading()
            getPresenter().importWalleByKeystoret()
        }
    }


    override fun initData() {
    }


    private fun getKeyStore(): String {
        return edKeyStore.text.toString().trim()
    }


    private fun getKeystorePwd(): String {
        return edKeyStorePwd.text.toString().trim()
    }

    override fun createPresenter(): ImportWalletPresenter? {
        return ImportWalletPresenter()
    }

    override fun createView(): ImportWalletView? {
        return this
    }

    override fun getContent(): String {
        return getKeyStore()
    }

    override fun getPassword(): String {
        return getKeystorePwd()
    }

    private var walletAddress: String = ""
    override fun importSuccess(wallet: ETHWallet) {
        hideLoading()
        OcWalletDetailActivity.startOcWalletDetailActivity(mContext, wallet)
        activity?.finish()

        //导入钱包成功之后 保存address
        saveMoneyAddress(wallet.address)
        saveWalletName(wallet.name)
        walletAddress = wallet.address
        getPresenter().login()
    }


    override fun setWalletAddress(): String {
        return walletAddress
    }

}
